#!/usr/bin/python3
#! -*- coding: utf8 -*-
# ID :VIrtualman 编写
import re
import os
import socket
import sys
import json
import json.encoder
import io
import pexpect
import datetime
import tojson

print("评测机启动成功，当前操作系统为："+sys.platform)
#GetDataFromServer()：获取服务器传递来的数据;

def GetDataFromServer(new_socket):
    data = new_socket.recv(5000000)
    print("收到的任务："+(data).decode())
    return ((data).decode())

def SendMesToServer(string,csocket):
    try:
        csocket.sendall(string.encode(encoding='utf-8'))
        print("评测结果返回成功！")
        return 1
    except:
        print("评测结果返回失败，具体原因不详！")
        return 0
def GetMemory(pid):
    pex2 = pexpect.spawn('/bin/bash', ['-c', 'ps -eo pid,size'])
    allstring = pex2.read().decode()
    lenstring = allstring.find(str(pid))
    # print(lenstring)
    # print(lenstring+len(str(pid)))
    #input()
    memory = allstring[lenstring + len(str(pid)):lenstring + len(str(pid)) + 6]
    memory = int(memory)
    return memory

def Evaluation(code,lan,n,data_in,data_out,data_memory,data_time):
    file_name=""
    if lan=='1':
        bash_bianyi = 'gcc'
        file_name="./a.c"
    if lan=='2':
        bash_bianyi = 'g++'
        file_name="./a.cpp"
    fp = open(file_name, 'w')
    #print(file_name)
    fp.write(code)
    fp.close()
    open('res.txt', 'w')
    for i in range(0,len(data_in)):
        print('正在进行第'+str(i+1)+'个数据点评测')
        inf_bianyi =os.system(bash_bianyi+' '+file_name)
        if (inf_bianyi==0):
            print("编译通过，开始运行！")
        else:
            print("CE")
            ce=1
            return
        shell_cmd = './a.out >>res.txt \n'
        pex = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
        start = datetime.datetime.now()
        all_res_memory[i] =GetMemory(pex.pid)
        pex.sendline(data_in[i])
        while(1):
            end = datetime.datetime.now()
            usetime = (end - start).microseconds / 1000+(end-start).seconds*1000-160
            #print("标准运行时间：" + data_time + "已运行：" + str(usetime))
            all_res_time[i] = usetime
            if(pex.isalive() and usetime>int(data_time)):
                all_res_ans[i] = "TLE"
                print("程序运行时间：" + str(usetime) + 'ms')
                pex.sendintr()
                print("TLE")
                break;
            if(pex.isalive()== False):
                break;
        try:
            if all_res_ans[i]=='TLE':
                continue;
        except:
            pass;
        if (all_res_memory[i] > int(data_memory)):
            all_res_ans[i] = 'MLE'
            print("MLE")
            pex.sendintr()
            print("程序运行空间：" + all_res_memory[i] + 'kb')
            continue
        #Return_Server_res("TLE")
        res=open('res.txt',"r").read()
        all_res_time[i] = usetime
        print("程序运行空间："+str(all_res_memory[i])+"B")
        print("程序运行时间："+str(all_res_time[i])+'ms')
        print("用户答案："+res+" 标准答案："+data_out[i])
        pex.sendintr()
        if str(res).split()==data_out[i].split():
            print("AC")
            all_res_ans[i]='AC'
        else:

            print("WA")
            all_res_ans[i]='WA'
        os.remove('res.txt')

ip=open("./data/host_ip.txt","r").read()
point = open("./data/host_point.txt","r").read()
address = (ip,int(point))
print("服务器地址："+ip+"端口："+point)
new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new_socket.connect(address)
for q in range(1,2):
    #变量初始化 Start：
    all_res_memory = {}
    all_res_time = {}
    all_res_ans={}
    errorcode="0"
    ce = 0
    #变量初始化 End;
    #JSON转换：
    data_json=json.loads(GetDataFromServer(new_socket))
    data_code = data_json['code']
    data_id = data_json['problemid']
    data_n = data_json['n']
    data_lan = data_json['lan']
    data_time = data_json['time']
    data_memory = data_json['memory']
    data_in=data_json['in']
    data_out=data_json['out']
    data_logid=data_json['logid']
    #下面开始启动评测函数
    print('开始评测：')
    Evaluation(data_code,data_lan,data_n,data_in,data_out,data_memory,data_time)
    #def Evaluation(code,lan,n,data_in,data_out,data_memory,all_res,all_res_time,all_res_memory)
    return_data = tojson.SendEvaluationAnsToServer(data_logid, ce,errorcode,all_res_ans,all_res_time,all_res_memory)
    SendMesToServer(return_data , new_socket)
    new_socket.close()


